<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const myCityData = proxy.$City
const attrs = ref([])
// ----
const advs = reactive({
  add: true,
  maxnum: 9,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
const isChinese = /^[\u4e00-\u9fa5]{2,4}$/
const form = reactive({
  name: '',
  sex: 1,
  age: '',
  addrCity: '',
  remark: '',
  demand: '',
  attr: ','
})

/* ---- */
const pickerDate = ref()
const pickerCity = ref()
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = async () => {
  advs.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / advs.forFree}px` }
  // --获取交友属性--
  const attrItems = forSys.filter((item) => { return String(item.name) === 'market_marryattrib' })
  if (Number(attrItems.length) === 1) {
    await proxy.$Myfun.getJsonData(attrItems[0].value, (resJson) => {
      const newItems = []
      resJson[0].list.forEach((item, index) => {
        newItems.push({
          value: String(item.id),
          text: proxy.$Myfun.setText(item.name)
        })
      })
      attrs.value = newItems
    })
  }
  // -- 获取动态信息 --
  if (proxy.$route.query.id) {
    const forMarryData = { params: { 'MarriageFrmSearch[id]': proxy.$route.query.id } }
    await proxy.$Axios.all([
      proxy.$Axios.get('marriage-frm/index', forMarryData)
    ]).then(proxy.$Axios.spread((marryData) => {
      const MData = marryData.items[0] || {}
      // ----
      form.name = MData.name
      if (Number(MData.gender) > 0) form.sex = MData.gender
      form.age = MData.age
      // ----
      let forCity = ''
      if (MData.district) {
        forCity = MData.province + ' - ' + MData.city + ' - ' + MData.district
      } else if (MData.city) {
        forCity = MData.province + ' - ' + MData.city
      } else if (MData.province) {
        forCity = MData.province
      }
      form.addrCity = forCity
      // ----
      form.remark = MData.remark
      form.demand = MData.demand
      if (MData.type && Number(MData.type.length) > 2) form.attr = MData.type
      // ----
      proxy.$Myfun.getJsonData(MData.image, (resJson) => {
        resJson.forEach((item) => {
          advs.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(advs.imgs.length) >= Number(advs.maxnum) && Number(advs.maxnum) > 0) advs.add = !advs.add
      })
    })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  document.querySelectorAll('.form-sex input[type="radio"]').forEach((item) => {
    if (Number(item.value) === Number(form.sex)) document.querySelector('.form-sex label[for="' + item.getAttribute('id') + '"]').querySelector('b').setAttribute('class', 'fa fa-dot-circle xw-color-12')
  })
  // ----
  attrs.value.some((current) => {
    if (String(current.value) === String(form.attr)) form.attrText = current.text
  })
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const curEL = item.currentTarget
      const parentEL = curEL.parentElement
      // ----
      parentEL.querySelectorAll('label').forEach((curItem) => { curItem.querySelector('b').setAttribute('class', 'fal fa-circle xw-color-16') })
      curEL.querySelector('b').setAttribute('class', 'fa fa-dot-circle xw-color-12')
      break
    }
    case 2: {
      const options = {
        opts: { beginYear: 1940, endYear: 2600, date: form.age },
        button: ['取消', '确定'],
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? '-' : '') + curItem.text
          })
          form.age = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerDate.value, 'open', options)
      break
    }
    case 3: {
      const options = {
        type: 3,
        button: ['取消', '确定'],
        initData: myCityData,
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? ' - ' : '') + curItem.text
          })
          form.addrCity = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerCity.value, 'open', options)
      break
    }
    case 4: {
      if (form.attr.indexOf(',' + item.value + ',') >= 0) {
        const reg = new RegExp(',' + item.value + ',', 'g')
        form.attr = form.attr.replace(reg, ',')
        return false
      }
      // ----
      form.attr = ',' + item.value + ','
      break
    }
  }
}
const subform = async () => {
  if (!isChinese.test(form.name)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写你的真实姓名！')
    return false
  }
  if (Number(form.age.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择出生日期！')
    return false
  }
  if (Number(form.addrCity.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择所属地区！')
    return false
  }
  if (Number(form.attr.split(',').length) <= 2) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择交友属性！')
    return false
  }
  // ----
  const forCity = form.addrCity.split(' - ')
  // ----
  let forAdvs = ''
  if (Number(advs.imgs.length) > 0) {
    const advItems = []
    advs.imgs.forEach((item, index) => {
      advItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forAdvs = JSON.stringify(advItems)
  }
  // ----
  let forType = 'post'
  let forUrl = 'marriage-frm/create'
  let forData = {
    dealer_id: logUser.id,
    telphone: logUser.telphone,
    // ----
    name: form.name,
    gender: form.sex,
    age: form.age,
    province: forCity[0],
    city: forCity[1],
    district: forCity[2],
    remark: form.remark,
    demand: form.demand,
    type: form.attr,
    image: forAdvs,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'marriage-frm/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      gender: form.sex,
      age: form.age,
      province: forCity[0],
      city: forCity[1],
      district: forCity[2],
      remark: form.remark,
      demand: form.demand,
      type: form.attr,
      image: forAdvs,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>你的姓名</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写你的真实姓名" v-model.trim="form.name"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.name"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>性别属性</i>
            <p class="xw-flex-W1"></p>
            <div class="form-sex xw-flex xw-flex-align">
              <input type="radio" id="male" value="1" v-model="form.sex"/>
              <input type="radio" id="female" value="2" v-model="form.sex"/>
              <label for="male" class="xw-flex xw-flex-align" @click="getAuditFun(1, $event)"><b class="fal fa-circle xw-color-16"></b>男</label>
              <label for="female" class="xw-flex xw-flex-align" @click="getAuditFun(1, $event)"><b class="fal fa-circle xw-color-16"></b>女</label>
            </div>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>出生日期</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.age" @click="getAuditFun(2)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.age"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>所属地区</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model="form.addrCity" @click="getAuditFun(3)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.addrCity"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>自我介绍</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.remark"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>对Ta要求</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.demand"></textarea></p>
          </div>
        </li>
        <li v-if="Number(attrs.length) > 0">
          <div class="form-more xw-radius-3">
            <h1>交友属性</h1>
            <dl>
              <dd class="form-more-W3" v-for="(item, index) in attrs" :class="{'active': Number(form.attr.indexOf(',' + item.value + ',')) !== Number(-1)}" @click="getAuditFun(4, item)"><div class="xw-radius-3"><span class="xw-block xw-ellipsis">{{item.text}}</span></div></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">个人照片</span>
              <span v-if="Number(advs.maxnum) > 0">数量：最多{{advs.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in advs.imgs"><label class="xw-block xw-act" :style="advs.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, advs, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, advs, index)"></span></dd>
              <dd class="xw-float-W3" v-if="advs.add"><label class="xw-act xw-flex xw-flex-center" :style="advs.setTrueStyle" @click="uploadAct(3, advs)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <pickerdate-view ref="pickerDate"/>
    <picker-view ref="pickerCity"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>